package hbase;

import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

/**
 * @author:huanqing.cheng
 * @time:2022/2/23 5:28 下午
 * @description:
 */
public class digestSaltedTest {
    public static void main(String[] args) {

        String orderID = "522522245";
        String saltedRowKey = saltRowKey(orderID, 2);
        System.out.println("Salted rowkey is " + saltedRowKey);

        String orderID2 = "617345555";
        String saltedRowKey2 = saltRowKey(orderID2, 2);
        System.out.println("Salted rowkey2 is " + saltedRowKey2);

        String orderID3 = "430040548";
        String saltedRowKey3 = saltRowKey(orderID3, 2);
        System.out.println("Salted rowkey3 is " + saltedRowKey3);

        String orderID4 = "224140439";
        String saltedRowKey4 = saltRowKey(orderID4, 2);
        System.out.println("Salted rowkey4 is " + saltedRowKey4);

        String orderID5 = "100000000";
        String saltedRowKey5 = saltRowKey(orderID5, 2);
        System.out.println("Salted rowkey5 is " + saltedRowKey5);

    }

    private static String saltRowKey(String rowkey, int suffixSize) {
        long id = Long.parseLong(rowkey);
        // If suffix size is 3, it means we want to take 3 digits, so we mod 1000
        // If suffix size is 2, it means we want to take 2 digits, so we mod 100
        // If suffix size is 1, it means we want to take 1 digit, so we mod 10
        // NOTE. no more than 4 digits for good
        long suffix = id % (suffixSize == 3 ? 1000 :
                suffixSize == 2 ? 100 :
                        10);

        // Pre-append 0 to avoid data skew, if the suffixSize > 1.
        String strSuffix = String.valueOf(suffix);
        strSuffix = (suffixSize == 3 ? "00" : suffixSize == 2 ? "0" : "") + strSuffix;
        System.out.println("Suffix for row key " + rowkey + " is " + strSuffix);

        StringBuilder builder = new StringBuilder();
        builder.append(strSuffix.substring(strSuffix.length() - suffixSize))    // Append the salt first
                .append(":")       // Add a delimiter or not it's up to you, better to do so
                .append(rowkey);   // Finally, we append the row key
        return builder.toString();
    }
}
